/*
 * GestioneLookUp2.java
 *
 * Created on 7 aprile 2007, 9.30
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package tlApp;

import fnUtils.IdDes;
import javax.swing.DefaultListModel;

/**
 *
 * @author franic
 */

public class GestioneLookUp2 extends GestioneLookUp1 {

    /**
     * Creates a new instance of GestioneLookUp2
     */
    public GestioneLookUp2() {
        super();
        butUp.setVisible(true);
        butDown.setVisible(true);
    }
    
    protected void fine() {
        boolean rcOK = false;
        int numItems = listModel.getSize();
        for (int i=0; i<numItems; i++){
            int id = ((IdDes)listModel.get(i)).getId();
            rcOK = ExecSQL.updateTab(GestioneDati.nomeTab, id, i+1);
            if (!rcOK) {
                lblMsg.setText("Update KO");
                break;
            }
        }
        if (rcOK) {
            super.fine();
        };
    }
    
    protected void butUpActionPerformed(java.awt.event.ActionEvent evt) {
        if (lstTab.getSelectedValue() == null) {
            lblMsg.setText("Selezionare una riga");
        } else {
            int moveMe = lstTab.getSelectedIndex();
            if (moveMe != 0) {
                int numItems = listModel.getSize();
                swap(moveMe, moveMe-1,listModel);
                lstTab.setModel(listModel);
                lstTab.setSelectedIndex(moveMe-1);
                lstTab.ensureIndexIsVisible(moveMe-1);
            }
        }
    }
    
    protected void butDownActionPerformed(java.awt.event.ActionEvent evt) {
        if (lstTab.getSelectedValue() == null) {
            lblMsg.setText("Selezionare una riga");
        } else {
            int moveMe = lstTab.getSelectedIndex();
            if (moveMe != listModel.getSize()-1) {
                int numItems = listModel.getSize();
                swap(moveMe, moveMe+1,listModel);
                lstTab.setModel(listModel);
                lstTab.setSelectedIndex(moveMe+1);
                lstTab.ensureIndexIsVisible(moveMe+1);
            }
        }
    }
    
    static void swap(int a, int b, DefaultListModel listModel) {
        Object aObject = listModel.getElementAt(a);
        Object bObject = listModel.getElementAt(b);
        listModel.set(a, bObject);
        listModel.set(b, aObject);
    }
    
    protected void formWindowClosing(java.awt.event.WindowEvent evt) {
        fine();
    }
    
    protected void butExitActionPerformed(java.awt.event.ActionEvent evt) {
        fine();
    }
}
